package com.yupi.questionai.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yupi.questionai.annotation.AuthCheck;
import com.yupi.questionai.common.BaseResponse;
import com.yupi.questionai.common.DeleteRequest;
import com.yupi.questionai.common.ErrorCode;
import com.yupi.questionai.common.ResultUtils;
import com.yupi.questionai.constant.UserConstant;
import com.yupi.questionai.exception.BusinessException;
import com.yupi.questionai.exception.ThrowUtils;
import com.yupi.questionai.model.dto.questionBankQuestion.QuestionBankQuestionAddRequest;
import com.yupi.questionai.model.dto.questionBankQuestion.QuestionBankQuestionQueryRequest;
import com.yupi.questionai.model.dto.questionBankQuestion.QuestionBankQuestionRemoveRequest;
import com.yupi.questionai.model.dto.questionBankQuestion.QuestionBankQuestionUpdateRequest;
import com.yupi.questionai.model.entity.QuestionBankQuestion;
import com.yupi.questionai.model.entity.User;
import com.yupi.questionai.model.vo.QuestionBankQuestionVO;
import com.yupi.questionai.service.QuestionBankQuestionService;
import com.yupi.questionai.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 题库题目关联接口
 *
 *
 * @from <a href="https://www.code-nav.cn">编程导航学习圈</a>
 */
@RestController
@RequestMapping("/questionBankQuestion")
@Slf4j
public class QuestionBankQuestionController {

    @Resource
    private QuestionBankQuestionService questionBankQuestionService;

    @Resource
    private UserService userService;

    // region 增删改查

    /**
     * 创建题库题目关联（仅管理员可用）
     * <p>
     * 该接口用于将题目与题库进行关联绑定，仅系统管理员有权限调用。
     * 关联关系创建后会记录创建者ID，用于数据追踪和权限控制。
     * </p>
     *
     * @param questionBankQuestionAddRequest 题库题目关联创建请求DTO
     *                                       <ul>
     *                                       <li>questionBankId: 题库ID（必填）- 待关联的目标题库唯一标识</li>
     *                                       <li>questionId: 题目ID（必填）- 待关联的目标题目唯一标识</li>
     *                                       <li>sortOrder: 排序序号（可选）- 题目在题库中的展示顺序，默认按创建时间排序</li>
     *                                       </ul>
     * @param request                       HTTP请求对象，用于获取当前登录用户上下文
     * @return BaseResponse<Long> 包含新创建的题库题目关联记录ID的成功响应
     */
    @PostMapping("/add")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Long> addQuestionBankQuestion(@RequestBody QuestionBankQuestionAddRequest questionBankQuestionAddRequest, HttpServletRequest request) {
        // 1. 参数非空校验：若请求DTO为null，抛出参数错误异常
        ThrowUtils.throwIf(questionBankQuestionAddRequest == null, ErrorCode.PARAMS_ERROR);

        // 2. DTO转实体：将请求DTO属性复制到数据库实体对象
        QuestionBankQuestion questionBankQuestion = new QuestionBankQuestion();
        BeanUtils.copyProperties(questionBankQuestionAddRequest, questionBankQuestion);

        // 3. 数据校验：调用Service层验证实体合法性（第二个参数true表示为新增场景校验）
        questionBankQuestionService.validQuestionBankQuestion(questionBankQuestion, true);

        // 4. 填充默认值：获取当前登录用户（管理员）并设置为关联记录的创建者ID
        User loginUser = userService.getLoginUser(request);
        questionBankQuestion.setUserId(loginUser.getId());

        // 5. 写入数据库：调用Service层保存实体，若保存失败抛出操作失败异常
        boolean result = questionBankQuestionService.save(questionBankQuestion);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);

        // 6. 返回结果：获取自动生成的关联记录ID并封装为成功响应
        long newQuestionBankQuestionId = questionBankQuestion.getId();
        return ResultUtils.success(newQuestionBankQuestionId);
    }


    /**
     * 删除题库题目关联
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteQuestionBankQuestion(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        QuestionBankQuestion oldQuestionBankQuestion = questionBankQuestionService.getById(id);
        ThrowUtils.throwIf(oldQuestionBankQuestion == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldQuestionBankQuestion.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = questionBankQuestionService.removeById(id);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 更新题库题目关联（仅管理员可用）
     *
     * @param questionBankQuestionUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateQuestionBankQuestion(@RequestBody QuestionBankQuestionUpdateRequest questionBankQuestionUpdateRequest) {
        if (questionBankQuestionUpdateRequest == null || questionBankQuestionUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // todo 在此处将实体类和 DTO 进行转换
        QuestionBankQuestion questionBankQuestion = new QuestionBankQuestion();
        BeanUtils.copyProperties(questionBankQuestionUpdateRequest, questionBankQuestion);
        // 数据校验
        questionBankQuestionService.validQuestionBankQuestion(questionBankQuestion, false);
        // 判断是否存在
        long id = questionBankQuestionUpdateRequest.getId();
        QuestionBankQuestion oldQuestionBankQuestion = questionBankQuestionService.getById(id);
        ThrowUtils.throwIf(oldQuestionBankQuestion == null, ErrorCode.NOT_FOUND_ERROR);
        // 操作数据库
        boolean result = questionBankQuestionService.updateById(questionBankQuestion);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 根据 id 获取题库题目关联（封装类）
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<QuestionBankQuestionVO> getQuestionBankQuestionVOById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        QuestionBankQuestion questionBankQuestion = questionBankQuestionService.getById(id);
        ThrowUtils.throwIf(questionBankQuestion == null, ErrorCode.NOT_FOUND_ERROR);
        // 获取封装类
        return ResultUtils.success(questionBankQuestionService.getQuestionBankQuestionVO(questionBankQuestion, request));
    }

    /**
     * 分页获取题库题目关联列表（仅管理员可用）
     *
     * @param questionBankQuestionQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<QuestionBankQuestion>> listQuestionBankQuestionByPage(@RequestBody QuestionBankQuestionQueryRequest questionBankQuestionQueryRequest) {
        long current = questionBankQuestionQueryRequest.getCurrent();
        long size = questionBankQuestionQueryRequest.getPageSize();
        // 查询数据库
        Page<QuestionBankQuestion> questionBankQuestionPage = questionBankQuestionService.page(new Page<>(current, size),
                questionBankQuestionService.getQueryWrapper(questionBankQuestionQueryRequest));
        return ResultUtils.success(questionBankQuestionPage);
    }

    /**
     * 分页获取题库题目关联列表（封装类）
     *
     * @param questionBankQuestionQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<QuestionBankQuestionVO>> listQuestionBankQuestionVOByPage(@RequestBody QuestionBankQuestionQueryRequest questionBankQuestionQueryRequest,
                                                               HttpServletRequest request) {
        long current = questionBankQuestionQueryRequest.getCurrent();
        long size = questionBankQuestionQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<QuestionBankQuestion> questionBankQuestionPage = questionBankQuestionService.page(new Page<>(current, size),
                questionBankQuestionService.getQueryWrapper(questionBankQuestionQueryRequest));
        // 获取封装类
        return ResultUtils.success(questionBankQuestionService.getQuestionBankQuestionVOPage(questionBankQuestionPage, request));
    }

    /**
     * 分页获取当前登录用户创建的题库题目关联列表
     *
     * @param questionBankQuestionQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<QuestionBankQuestionVO>> listMyQuestionBankQuestionVOByPage(@RequestBody QuestionBankQuestionQueryRequest questionBankQuestionQueryRequest,
                                                                 HttpServletRequest request) {
        ThrowUtils.throwIf(questionBankQuestionQueryRequest == null, ErrorCode.PARAMS_ERROR);
        // 补充查询条件，只查询当前登录用户的数据
        User loginUser = userService.getLoginUser(request);
        questionBankQuestionQueryRequest.setUserId(loginUser.getId());
        long current = questionBankQuestionQueryRequest.getCurrent();
        long size = questionBankQuestionQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<QuestionBankQuestion> questionBankQuestionPage = questionBankQuestionService.page(new Page<>(current, size),
                questionBankQuestionService.getQueryWrapper(questionBankQuestionQueryRequest));
        // 获取封装类
        return ResultUtils.success(questionBankQuestionService.getQuestionBankQuestionVOPage(questionBankQuestionPage, request));
    }


    /**
     * 移除题库与题目的关联关系
     *
     * @param questionBankQuestionRemoveRequest 移除请求对象，包含需要移除关联关系的题库ID和题目ID
     * @return BaseResponse<Boolean> 操作结果，true表示移除成功，false表示移除失败
     */
    @PostMapping("/remove")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> removeQuestionBankQuestion(
            @RequestBody QuestionBankQuestionRemoveRequest questionBankQuestionRemoveRequest
    ) {
        // 参数校验 - 检查请求对象是否为null
        ThrowUtils.throwIf(questionBankQuestionRemoveRequest == null, ErrorCode.PARAMS_ERROR);

        // 从请求对象中获取题库ID和题目ID
        Long questionBankId = questionBankQuestionRemoveRequest.getQuestionBankId();  // 题库ID，标识要移除关联关系的题库
        Long questionId = questionBankQuestionRemoveRequest.getQuestionId();         // 题目ID，标识要移除关联关系的题目

        // 参数校验 - 检查题库ID和题目ID是否为null
        ThrowUtils.throwIf(questionBankId == null || questionId == null, ErrorCode.PARAMS_ERROR);

        // 构造查询条件 - 使用LambdaQueryWrapper构建查询条件
        LambdaQueryWrapper<QuestionBankQuestion> lambdaQueryWrapper = Wrappers.lambdaQuery(QuestionBankQuestion.class)
                // 设置第一个查询条件：题库ID等于传入的题库ID，确保只操作指定题库的关联关系
                .eq(QuestionBankQuestion::getQuestionBankId, questionBankId)
                // 设置第二个查询条件：题目ID等于传入的题目ID，确保只操作指定题目的关联关系
                .eq(QuestionBankQuestion::getQuestionId, questionId);

        // 执行删除操作 - 根据构造的查询条件删除题库与题目的关联关系
        boolean result = questionBankQuestionService.remove(lambdaQueryWrapper);

        // 返回操作结果 - 封装操作结果为BaseResponse返回给前端
        return ResultUtils.success(result);
    }


    // endregion
}
